package cn.codergege.demo.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file-load")
public class LoadController implements ServletContextAware {
   private final Logger log = LoggerFactory.getLogger(LoadController.class);

   @Autowired
   private ServletContext servletContext;

   @RequestMapping("/upload")
   public String uploadPage() {
      return "file-load/upload-page";
   }
   @RequestMapping(value = "/upload", method = RequestMethod.POST)
   public String upload(@RequestPart("pic") MultipartFile[] files) {

      try {
         log.info("上传图片数量: " + files.length);
          for(MultipartFile file : files) {
             log.info("getName(): " + file.getName());
             log.info("getOriginalFileName(): " + file.getOriginalFilename());
             log.info("getContentType(): " + file.getContentType());
             log.info("getSize() " + file.getSize());
             // 还可以加上时间戳来防止同名覆盖
             file.transferTo(new File(servletContext.getRealPath("/")
                     + "/upload/pic/"
                     + file.getOriginalFilename()));
          }
      } catch (IOException e) {
         e.printStackTrace();
         // todo: to error page
      }

      // todo: to pic page
      return "redirect:/";
   }

   // todo: download

   @Override
   public void setServletContext(ServletContext servletContext) {
      this.servletContext = servletContext;
   }
}
